<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>排序算法</title>
</head>

<body>
  <script>
    // 封装数据
    function ArrayList() {
      this.array = []
      ArrayList.prototype.insert = function (item) {
        this.array.push(item)
      }
      ArrayList.prototype.toString = function () {
        return this.array.join('-')
      }
    }
    // 实现排序算法
    // 交换数据位置
    ArrayList.prototype.swap = function (m, n) {
      let temp = this.array[m]
      this.array[m] = this.array[n]
      this.array[n] = temp
    }
    // 冒泡排序
    ArrayList.prototype.bubbleSort = function () {
      let length = this.array.length - 1
      for (let j = length; j >= 0; j--) {
        for (let i = 0; i < j; i++) {
          if (this.array[i] > this.array[i + 1]) {
            // 交换数据
            this.swap(i, i + 1)
          }
        }
      }
    }
    // 选择排序
    ArrayList.prototype.selectionSort = function () {
      var length = this.array.length
      for (var j = 0; j < length - 1; j++) {
        var min = j
        for (var i = min + 1; i < length; i++) {
          if (this.array[min] > this.array[i]) {
            min = i
          }
        }
        this.swap(min, j)
      }
    }
    // 插入排序
    ArrayList.prototype.insertionSort = function () {
      var length = this.array.length
      for (let i = 1; i < length; i++) {
        let temp = this.array[i]
        let j = i
        while (this.array[j - 1] > temp && j > 0) {
          this.array[j] = this.array[j - 1]
          j--
        }
        this.array[j] = temp
      }
    }
    // 希尔排序
    // 快速排序




    // 初始化数据
    const list = new ArrayList()
    list.insert(3)
    list.insert(6)
    list.insert(4)
    list.insert(2)
    list.insert(11)
    list.insert(110)
    list.insert(130)
    list.insert(120)
    list.insert(1450)
    list.insert(10)
    list.insert(160)
    list.insert(107)
    list.insert(1880)
    list.insert(5)

    // alert(list)
    list.insertionSort()
    alert(list)

  </script>
</body>

</html>